/*   **********************************************************************  **
 **   Copyright notice                                                       **
 **                                                                          **
 **   (c) 2009, Around(J2)ME				                                 **
 **   All rights reserved.                                                   **
 **                                                                          **
 **   This program and the accompanying materials are made available under   **
 **   the terms of the New BSD License which accompanies this    			 **
 **   distribution.											                 **
 **   A copy is found in the textfile LICENSE.txt							 **
 **                                                                          **
 **   This copyright notice MUST APPEAR in all copies of the file!           **
 **                                                                          **
 **   Main developers:                                                       **
 **     Juri Strumpflohner		http://blog.js-development.com	             **
 **		Matthias Braunhofer		http://matthias.jimdo.com                    **
 **                                                                          **
 **  **********************************************************************  */

package com.aroundj2me.utility;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

import com.aroundj2me.model.Messages;

public class HttpCommunicator {

	/**
	 * Executes an HTTP GET connection and reads the data in a byte[] that is
	 * returned to the caller
	 * 
	 * @param url
	 *            the URL to which to connect
	 * @return byte[] containing the retrieved data, null if the call failed
	 * @throws Exception
	 */
	public static byte[] executeHTTPGet(String url) throws Exception {
		byte[] result = null;
		
		InputStream in = null;
		HttpConnection hc = null;

		try {
			hc = (HttpConnection) Connector.open(url);
			hc.setRequestMethod(HttpConnection.GET);

			if (hc.getResponseCode() == HttpConnection.HTTP_OK) {
				in = hc.openInputStream();

				int length = (int) hc.getLength();
				if (length > 0) {
					result = new byte[length];
					int processed = 0;
					while (processed < length) {
						processed += in.read(result, processed, length
								- processed);
					}
				} else {
					ByteArrayOutputStream bos = new ByteArrayOutputStream();
					byte[] buffer = new byte[512];
					int count;
					while ((count = in.read(buffer)) >= 0) {
						bos.write(buffer, 0, count);
					}
					result = bos.toByteArray();
				}

			} else {
				throw new Exception(Messages.SERVER_CONNECTION_FAILED);
			}

		} catch (Exception e) {
			if (e.getMessage().equals(""))
				throw new Exception(Messages.SERVER_CONNECTION_FAILED);
			else
				throw e; // TODO throw just "user-friendly" message?
		} finally {
			try {
				if (in != null)
					in.close();
				if (hc != null)
					hc.close();
			} catch (IOException ioe) {
			}
		}

		return result;
	}

	/**
	 * Used to encode the URL parameters, e.g. that they don't contain any whitespace or 
	 * other characters that are not supported by HTTP GET requests
	 * @param str
	 * @return
	 */
	public static String urlEncode(String str) {
		if (str == null)
			return null;

		StringBuffer resultStr = new StringBuffer(str.length());
		char tmpChar;
		
		for (int ix = 0; ix < str.length(); ix++) {
			tmpChar = str.charAt(ix);
			switch (tmpChar) {
			case ' ':
				resultStr.append("%20");
				break;
			case '-':
				resultStr.append("%2D");
				break;
			case '/':
				resultStr.append("%2F");
				break;
			case ':':
				resultStr.append("%3A");
				break;
			case '=':
				resultStr.append("%3D");
				break;
			case '?':
				resultStr.append("%3F");
				break;
			case '#':
				resultStr.append("%23");
				break;
			case '\r':
				resultStr.append("%0D");
				break;
			case '\n':
				resultStr.append("%0A");
				break;
			default:
				resultStr.append(tmpChar);
				break;
			}
		}
		return resultStr.toString();
	}
}
